<template>
  <div class="center-container">
    <PersonHead :tabs="tabs" @tabClick="handleTabClick" />
    <div>
      <component 
        :is="currentTabComp" 
        :orderList="orderList" 
        :loading="loading" 
        @orderCanceled="handleOrderCanceled" 
        @refreshOrders="handleRefreshOrders"
      />
    </div>
    <div class="pagination" v-if="!paginationHideList.includes('personData')">
      <Pagination :total="total" :current-page="page" :page-size="pageSize" @page-change="handlePageChange" />
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { myOrderList } from "@/service/personalCenter";
import PersonHead from "@/components/PersonHead";
import Pagination from "@/components/Pagination";
import AllOrder from "./AllOrder";
import Canceled from "./Canceled";
import TodoPay from "./TodoPay";
import Finished from "./Finished";

// 设置默认显示全部订单
const currentTabComp = ref(AllOrder);
const paginationHideList = ref([]);
const orderList = ref([]);
const loading = ref(false);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const currentStatus = ref(0);

const tabs = ref([
  {
    label: "全部订单",
    type: "allOrder",
  },
  {
    label: "已完成",
    type: "finished",
  },
  {
    label: "待支付",
    type: "todoPay",
  },
  {
    label: "已取消",
    type: "canceled",
  },
]);

const handleTabClick = ({ item: { type } }) => {
  paginationHideList.value = [type];
  loading.value = false;
  const componentKeys = {
    allOrder: AllOrder,
    finished: Finished,
    todoPay: TodoPay,
    canceled: Canceled,
  };
  
  // 设置不同标签页对应的订单状态
  const statusMap = {
    allOrder: 0,
    finished: 2,
    todoPay: 1,
    canceled: 4
  };
  
  currentStatus.value = statusMap[type] || 0;
  currentTabComp.value = componentKeys[type];
  
  // 切换标签时重置页码并请求数据
  page.value = 1;
  fetchOrderList();
};

const fetchOrderList = async () => {
  try {
    loading.value = true;
    const params = {
      page: page.value,
      rows: pageSize.value,
      status: currentStatus.value
    };
    
    const res = await myOrderList(params);
    if (res && res.data) {
      orderList.value = res.data.result || [];
      total.value = res.data.totalCount || 0;
    }
  } catch (error) {
    console.error("获取订单列表失败", error);
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (newPage) => {
  page.value = newPage;
  fetchOrderList();
};

const handleOrderCanceled = () => {
  // 订单取消后刷新列表
  fetchOrderList();
};

const handleRefreshOrders = () => {
  // 支付成功后刷新订单列表
  fetchOrderList();
};

// 初始化时调用一次获取订单列表
onMounted(() => {
  fetchOrderList();
});
</script>

<style scoped lang="scss">
.center-container {
}
.pagination {
  margin-bottom: 15px !important;
}
</style>
